/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

/**
 * 
 */
package edu.ucla.cs.typecast.cache2;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

import edu.ucla.cs.typecast.net.EndPoint;
import edu.ucla.cs.typecast.net.EndPointListener;
import edu.ucla.cs.typecast.net.EndPointListenerFactory;
import edu.ucla.cs.typecast.net.NetUtil;
import edu.ucla.cs.typecast.rmi.Fact;
import edu.ucla.cs.typecast.rmi.Future;
import edu.ucla.cs.typecast.rmi.TypeCastClient;
import edu.ucla.cs.typecast.rmi.TypeCastServer;
import edu.ucla.cs.typecast.scope.HostScope;

/**
 *
 * @date Aug 21, 2007
 */
public class CacheAccessControl implements CacheService, ContentCacheService {
	private EndPoint cacheEndPoint; 
	private EndPoint contentEndPoint; 
	private Hashtable<CacheKey, CachedObject> cache = new Hashtable<CacheKey, CachedObject>(); 
	private Timer timer = new Timer(); 
	
	public CacheAccessControl(EndPoint cacheEndPoint) throws IOException { 
		this.cacheEndPoint = cacheEndPoint; 
		// Construct a private EndPoint to export ContentCacheService
		TypeCastServer tserver = new TypeCastServer(null); 
		this.contentEndPoint = tserver.getEndPoint(); 
		tserver.export(ContentCacheService.class, this); 		
		tserver = new TypeCastServer(cacheEndPoint); 
		tserver.export(CacheService.class, this); 
	}
	
	public void requestCache(EndPoint contentSourceEndPoint, CacheObjectDescription objectDesp) throws IOException { 
		CachedObject cacheObject = new CachedObject(); 
		cacheObject.setContentSourceEndPoint(contentSourceEndPoint); 
		cacheObject.setGuid(objectDesp.getGUID()); 
		cacheObject.setImplementationClass(objectDesp.getImplementationClass()); 
		cacheObject.setTypes(objectDesp.getTypes()); 
		cacheObject.setTimeout(new Date( new Date().getTime() + objectDesp.getTimeout() * 1000));
		CacheKey key = new CacheKey(cacheObject.getGuid(), contentSourceEndPoint); 
		if(!cache.contains(cacheObject)) { 
			cache.put(key, cacheObject); 
			TypeCastClient tclient = new TypeCastClient(contentSourceEndPoint); 
			ContentSource contentSource = (ContentSource)tclient.getTypeCastInvocationHandler(ContentSource.class); 
			contentSource.requestContent(contentEndPoint, cacheObject.getGuid()); 
		}
	}
	
	public void cacheObject(EndPoint contentSourceEndPoint,  CacheObjectDescription objectDesp, byte[] content) throws IOException { 
		final CacheKey key = new CacheKey(objectDesp.getGUID(), contentSourceEndPoint); 
		final CachedObject object = cache.get(key); 
		if (object != null && object.getServiceObject() == null && objectDesp.getTimeout() > 0) { 
			try { 
				ObjectInputStream ostream = new ObjectInputStream(new ByteArrayInputStream(content)); 
				Object serviceObject = ostream.readObject(); 
				object.setServiceObject(serviceObject); 
				//Now expose the object as TypeCast service
				final TypeCastServer tserver = new TypeCastServer(cacheEndPoint); 
				tserver.export(object.getTypes(), object.getServiceObject()); 
				//@TODO: schedule a timer task to unexport the object when timeout
				TimerTask expireTask = new TimerTask() { 
					public void run() { 
						try { 							
							cache.remove(key); 
							tserver.unexport(object.getServiceObject()); 
						} catch(Throwable t) { 
							t.printStackTrace(); 
						}
					}
				}; 
				timer.schedule(expireTask,  objectDesp.getTimeout() * 1000); 
			} catch(Throwable t) { 
				t.printStackTrace(); 
			}
		}
	}
	
	public Collection<CachedObject> getCachedObjects() { 
		return cache.values(); 
	}
	
	public Future<HostScope> getCacheHost(CacheKey objectDesp) { 
		if (cache.get(objectDesp) != null) { 
			HostScope thisHost = new HostScope(NetUtil.getLocalHost()); 
			return new Fact<HostScope>(thisHost); 
		}
		return null; 
	}

}
